<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="租户ID" prop="rechargeTenantId">
        <el-select
          v-model="queryParams.rechargeTenantId"
          placeholder="请选择租户ID"
          clearable
          class="!w-240px"
        >
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>

      <!-- 请求编码 -->
      <el-form-item label="请求编码" prop="requestNumber">
        <el-input
          v-model="queryParams.requestNumber"
          placeholder="请输入请求编码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <!-- 新增：调用IP（可搜索） -->
      <el-form-item label="调用IP" prop="requestIp">
        <el-input
          v-model="queryParams.requestIp"
          placeholder="请输入调用IP（支持模糊）"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>

      <el-form-item label="请求URL" prop="url">
        <el-input
          v-model="queryParams.url"
          placeholder="请输入请求URL"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="请求参数" prop="params">
        <el-input
          v-model="queryParams.params"
          placeholder="请输入请求参数"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="请求返回" prop="respons">
        <el-input
          v-model="queryParams.respons"
          placeholder="请输入请求返回"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="请求类型" prop="requestType">
        <el-select
          v-model="queryParams.requestType"
          placeholder="请选择请求类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.REQUEST_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="单价(元)" prop="unitPrice">
        <el-input
          v-model="queryParams.unitPrice"
          placeholder="请输入单价(元)"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="后余额" prop="afterBalance">
        <el-input
          v-model="queryParams.afterBalance"
          placeholder="请输入请求后的余额(元)"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['vos:tenant-request-log:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
    >
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="租户ID" align="center" prop="rechargeTenantId" />
      <el-table-column label="请求编码" align="center" prop="requestNumber" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="请求URL" align="center" prop="url" />
      <el-table-column label="请求参数" align="center" prop="params" />
      <el-table-column label="请求返回" align="center" prop="respons" />
      <el-table-column label="请求类型" align="center" prop="requestType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.REQUEST_TYPE" :value="scope.row.requestType" />
        </template>
      </el-table-column>

      <!-- 新增：调用IP（展示列） -->
      <el-table-column label="调用IP" align="center" prop="requestIp" />

      <!-- 新增：密钥ID（仅展示，不参与搜索） -->
      <el-table-column label="密钥ID" align="center" prop="secretId" />

      <el-table-column label="单价(元)" align="center" prop="unitPrice" />
      <el-table-column label="请求后的余额(元)" align="center" prop="afterBalance" />
    </el-table>

    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
</template>

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { TenantRequestLogApi, type TenantRequestLog } from '@/api/vos/tenantrequestlog'

defineOptions({ name: 'TenantRequestLog' })

const message = useMessage()

const loading = ref(true)

/** 扩展类型，兼容后端未及时补字段的情况 */
type TenantRequestLogEx = TenantRequestLog & {
  requestNumber?: string
  requestIp?: string
  secretId?: number
}

const list = ref<TenantRequestLogEx[]>([])
const total = ref(0)
const queryParams = reactive<any>({
  pageNo: 1,
  pageSize: 10,
  rechargeTenantId: undefined,
  /** 请求编码（数据库字段 request_number） */
  requestNumber: undefined,
  /** 新增：调用IP（数据库字段 request_ip） */
  requestIp: undefined,
  createTime: [],
  url: undefined,
  params: undefined,
  respons: undefined,
  requestType: undefined,
  unitPrice: undefined,
  afterBalance: undefined
})
const queryFormRef = ref()
const exportLoading = ref(false)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await TenantRequestLogApi.getTenantRequestLogPage(queryParams)
    list.value = data.list || []
    total.value = data.total || 0
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields?.()
  handleQuery()
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await TenantRequestLogApi.exportTenantRequestLog(queryParams)
    download.excel(data, '租户请求日志.xls')
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
